﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EffiProz.Core.Store;

namespace EffiProz.Core.Lib
{
    public class OrderedIntHashSet : BaseHashMap
    {
        public OrderedIntHashSet()
            : this(8)
        {

        }

        public OrderedIntHashSet(int initialCapacity)
            : base(initialCapacity, BaseHashMap.intKeyOrValue,
                BaseHashMap.noKeyOrValue, false)
        {
            isList = true;
        }

        public bool contains(int key)
        {
            return base.containsKey(key);
        }

        public bool add(int key)
        {

            int oldSize = size();

            base.addOrRemove(key, 0, null, null, false);

            return oldSize != size();
        }

        public bool remove(int key)
        {

            int oldSize = size();

            base.addOrRemove(key, 0, null, null, true);

            bool result = oldSize != size();

            if (result)
            {
                int[] array = toArray();

                base.clear();

                for (int i = 0; i < array.Length; i++)
                {
                    add(array[i]);
                }
            }

            return result;
        }

        public int get(int index)
        {

            checkRange(index);

            return intKeyTable[index];
        }

        public int getOrderedMatchCount(int[] array)
        {

            int i = 0;

            for (; i < array.Length; i++)
            {
                if (!base.containsKey(array[i]))
                {
                    break;
                }
            }

            return i;
        }

        public int[] toArray()
        {

            int lookup = -1;
            int[] array = new int[size()];

            for (int i = 0; i < array.Length; i++)
            {
                lookup = base.nextLookup(lookup);

                int value = intKeyTable[lookup];

                array[i] = value;
            }

            return array;
        }

        private void checkRange(int i)
        {

            if (i < 0 || i >= size())
            {
                throw new IndexOutOfRangeException();
            }
        }
    }
}
